package com.threeti.jiayusms.infrastructure.communicationlog;

import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static org.hibernate.criterion.Restrictions.disjunction;
import static org.hibernate.criterion.Restrictions.like;
import static org.springframework.util.CollectionUtils.isEmpty;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.threeti.jiayusms.domain.model.legacy.CommunicationLog;
import com.threeti.jiayusms.framework.dao.AbstractCustomKeyDao;
import com.threeti.jiayusms.framework.util.DynaSearchCriteria;
import com.threeti.jiayusms.framework.util.PagedListHandler;
import com.threeti.jiayusms.interfaces.LogTemplateDynaCriteria;

@Repository
public class CommunicationLogDaoImpl extends AbstractCustomKeyDao<String, CommunicationLog> implements CommunicationLogDao {
	@Autowired
	public CommunicationLogDaoImpl(@Qualifier("sessionFactoryExternal") SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	@Override
	protected DetachedCriteria buildDefaultCriteria() {
		return DetachedCriteria.forClass(CommunicationLog.class);
	}
	
	@Override
	public PagedListHandler<CommunicationLog> findAllLogTemplatesByPage(int currentPageIndex, int startingIndex) {
    DetachedCriteria criteria = buildDefaultCriteria();

    long totalSize = getTotalRowCountByCriteria(criteria);
    
    criteria.addOrder(Order.desc("this.communicationDate"));

    PagedListHandler<CommunicationLog>  pagedListHandler = 
      this.findByPageWithPassedInTotalRowCount(criteria, currentPageIndex, startingIndex, totalSize);
    
    List<CommunicationLog> pagedList = pagedListHandler.getPageList();
    if (!isEmpty(pagedList))  return pagedListHandler;

    return PagedListHandler.EMPTY_LIST;
	}
	
	@Override
	public PagedListHandler<CommunicationLog> findLogTemplatesByPage(DynaSearchCriteria dynaSearchCriteria, int currentPageIndex, int startingIndex) {
		LogTemplateDynaCriteria dynaCriteria = (LogTemplateDynaCriteria)dynaSearchCriteria;
		
		String templateKeywords = dynaCriteria.getTemplateKeywords();

		//模糊查询
		DetachedCriteria criteria = buildDefaultCriteria();
		
		String bdepartment = dynaCriteria.getBdepartment();
		try {
      if(isNotEmpty(bdepartment)){
      	criteria.add(Restrictions.like("this.bdepartment", "%" + new String(bdepartment.getBytes("iso8859-1"), "utf-8") + "%"));
      }
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
    }
		String carryId = dynaCriteria.getCarryId();
		try {
      if(isNotEmpty(carryId)){
      	criteria.add(Restrictions.like("this.carryId", "%" + new String(carryId.getBytes("iso8859-1"), "utf-8") + "%"));
      }
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
    }
		String clientName = dynaCriteria.getClientName();
		try {
      if(isNotEmpty(clientName)){
      	criteria.add(Restrictions.like("this.clientName", "%" + new String(clientName.getBytes("iso8859-1"), "utf-8") + "%"));
      }
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    
		String communicationDate = dynaCriteria.getCommunicationDate();
		if(isNotEmpty(communicationDate)){
			criteria.add(Restrictions.sqlRestriction("datepart(yyyy,create_date)=?", communicationDate.substring(0, 4), Hibernate.STRING));
			criteria.add(Restrictions.sqlRestriction("datepart(mm,create_date)=?", communicationDate.substring(5, 7), Hibernate.STRING));
			criteria.add(Restrictions.sqlRestriction("datepart(dd,create_date)=?", communicationDate.substring(8, 10), Hibernate.STRING));
		}
		String communicationFlag = dynaCriteria.getCommunicationFlag();
		if(isNotEmpty(communicationFlag)){
			criteria.add(Restrictions.eq("this.communicationFlag", communicationFlag));
		}
		String communicationMode = dynaCriteria.getCommunicationMode();
		if(isNotEmpty(communicationMode)){			
			criteria.add(Restrictions.eq("this.communicationMode", communicationMode));
		}
		String modifyUser = dynaCriteria.getModifyUser();
		if(isNotEmpty(modifyUser)){
			try {
				criteria.add(Restrictions.like("this.modifyUser", "%" + new String(modifyUser.getBytes("iso8859-1"), "utf-8") + "%"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String truckId = dynaCriteria.getTruckId();
		try {
      if(isNotEmpty(truckId)){
      	criteria.add(Restrictions.like("this.truckId", "%" + new String(truckId.getBytes("iso8859-1"), "utf-8") + "%"));
      }
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
		try {
      if(isNotEmpty(templateKeywords)){
      	String[] keywords = templateKeywords.split(" ");
      	Junction orClause = disjunction();
      	for (int i = 0; i < keywords.length; i++) {
          String encodeKeyWord = new String(keywords[i].getBytes("iso8859-1"), "utf-8");
      		String keyword = "%" + encodeKeyWord + "%";
      		orClause.add(like("this.customId", keyword).ignoreCase());
      	}
      	criteria.add(orClause);
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    long totalSize = getTotalRowCountByCriteria(criteria);
    
    criteria.addOrder(Order.desc("this.communicationDate"));

		PagedListHandler<CommunicationLog>  pagedListHandler = 
		  this.findByPageWithPassedInTotalRowCount(criteria, currentPageIndex, startingIndex, totalSize);
		
    List<CommunicationLog> pagedList = pagedListHandler.getPageList();
    if (!isEmpty(pagedList))  return pagedListHandler;

    return PagedListHandler.EMPTY_LIST;
	}
	
	
	@Override
	public List<CommunicationLog> findLogTemplatesByList(DynaSearchCriteria dynaSearchCriteria) {
		LogTemplateDynaCriteria dynaCriteria = (LogTemplateDynaCriteria)dynaSearchCriteria;
		
		

		//模糊查询
		DetachedCriteria criteria = buildDefaultCriteria();
		
		String bdepartment = dynaCriteria.getBdepartment();
		if(isNotEmpty(bdepartment)){
			try {
				criteria.add(Restrictions.like("this.bdepartment", "%" + new String(bdepartment.getBytes("iso8859-1"), "utf-8") + "%"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String carryId = dynaCriteria.getCarryId();
		if(isNotEmpty(carryId)){
			try {
				criteria.add(Restrictions.like("this.carryId", "%" + new String(carryId.getBytes("iso8859-1"), "utf-8") + "%"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String clientName = dynaCriteria.getClientName();
		if(isNotEmpty(clientName)){
			try {
				criteria.add(Restrictions.like("this.clientName", "%" + new String(clientName.getBytes("iso8859-1"), "utf-8") + "%"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String communicationDate = dynaCriteria.getCommunicationDate();
		if(isNotEmpty(communicationDate)){
			criteria.add(Restrictions.sqlRestriction("datepart(yyyy,start_time)=?", communicationDate.substring(0, 4), Hibernate.STRING));
			criteria.add(Restrictions.sqlRestriction("datepart(mm,start_time)=?", communicationDate.substring(5, 7), Hibernate.STRING));
			criteria.add(Restrictions.sqlRestriction("datepart(dd,start_time)=?", communicationDate.substring(8, 10), Hibernate.STRING));	
		}
		String communicationFlag = dynaCriteria.getCommunicationFlag();
		if(isNotEmpty(communicationFlag)){
			criteria.add(Restrictions.eq("this.communicationFlag", communicationFlag));
		}
		String communicationMode = dynaCriteria.getCommunicationMode();
		if(isNotEmpty(communicationMode)){			
			criteria.add(Restrictions.eq("this.communicationMode", communicationMode));
		}
		String modifyUser = dynaCriteria.getModifyUser();
		if(isNotEmpty(modifyUser)){
			try {
				criteria.add(Restrictions.like("this.modifyUser", "%" + new String(modifyUser.getBytes("iso8859-1"), "utf-8") + "%"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String truckId = dynaCriteria.getTruckId();
		if(isNotEmpty(truckId)){
			try {
				criteria.add(Restrictions.like("this.truckId", "%" + new String(truckId.getBytes("iso8859-1"), "utf-8") + "%"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String templateKeywords = dynaCriteria.getTemplateKeywords();
		if(isNotEmpty(templateKeywords)){
	    try {
	      templateKeywords = new String(templateKeywords.getBytes("iso8859-1"), "utf-8");
	    } catch (UnsupportedEncodingException e) {
	      e.printStackTrace();
	    }
			String[] keywords = templateKeywords.split(" ");
			Junction orClause = disjunction();
			for (int i = 0; i < keywords.length; i++) {
				String keyword = "%" + keywords[i] + "%";
				orClause.add(like("this.customId", keyword).ignoreCase());
			}
			criteria.add(orClause);
		}
    
    criteria.addOrder(Order.desc("this.communicationDate"));

		List<CommunicationLog>  allList = this.findAllBy(criteria);
    if (!isEmpty(allList))  return allList;

    return Collections.emptyList();
	}
	
}
